package me.zhengjie.modules.system.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import me.zhengjie.modules.system.domain.*;
import me.zhengjie.modules.system.domain.dto.PokerActivateInfoQueryCriteria;
import me.zhengjie.modules.system.mapper.PokerActivateInfoMapper;
import me.zhengjie.modules.system.service.*;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import me.zhengjie.utils.PageUtil;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import me.zhengjie.utils.PageResult;

/**
* @description 服务实现
* @author greazy
* @date 2025-04-07
**/
@Service
@RequiredArgsConstructor
public class PokerActivateInfoServiceImpl extends ServiceImpl<PokerActivateInfoMapper, PokerActivateInfo> implements PokerActivateInfoService {

    private final PokerActivateInfoMapper pokerActivateInfoMapper;

    private final PokerUserActivatInfoService userActivatInfoService;

    private final UserService userService;

    private final PokerAwardService pokerAwardService;

    private final PokerActivateAwardInfoService activateAwardInfoService;

    private final KingTeamVoteService kingTeamVoteService;
    private  final PokerGoodInfoService goodInfoService;


    @Override
    public PageResult<PokerActivateInfo> queryAll(PokerActivateInfoQueryCriteria criteria, Page<Object> page){
        return PageUtil.toPage(pokerActivateInfoMapper.findAll(criteria, page));
    }

    @Override
    public List<PokerActivateInfo> queryAll(PokerActivateInfoQueryCriteria criteria){
        return pokerActivateInfoMapper.findAll(criteria);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(PokerActivateInfo resources) {
        pokerActivateInfoMapper.insert(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(PokerActivateInfo resources) {
        PokerActivateInfo pokerActivateInfo = getById(resources.getId());
        pokerActivateInfo.copy(resources);
        pokerActivateInfoMapper.updateById(pokerActivateInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(List<Integer> ids) {
        pokerActivateInfoMapper.deleteBatchIds(ids);
    }

    @Override
    public void download(List<PokerActivateInfo> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (PokerActivateInfo pokerActivateInfo : all) {

        Map<String,Object> map = new LinkedHashMap<>();
            map.put("活动名称", pokerActivateInfo.getName());
            map.put("pubPoker1",  pokerActivateInfo.getPubPoker1());
            map.put("pubPoker2",  pokerActivateInfo.getPubPoker2());
            map.put("换牌所需基础筹码数量", pokerActivateInfo.getChangePokerBaseNum());
            map.put("每次换牌需要增加筹码数量", pokerActivateInfo.getChangePokerAddNum());
            map.put("免费换牌次数", pokerActivateInfo.getActiveFreeChage());
            map.put("最大换牌次数", pokerActivateInfo.getActiveMaxChage());
            map.put("前多少名", pokerActivateInfo.getFontPrizeNum());
            map.put("前多少名奖品", pokerActivateInfo.getFontPrizeNumGoodid());
            map.put("前三名奖品", pokerActivateInfo.getFontPrizeThirdGoodid());
            map.put("特殊物品", pokerActivateInfo.getSpecialGoodid());
            map.put("活动截止时间", pokerActivateInfo.getEndTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    @Transactional
    public void startActivate(Integer id) {
        PokerActivateInfo pokerActivateInfo = pokerActivateInfoMapper.selectById(id);
        String taskid = RandomUtil.randomStringUpper(15);
        pokerActivateInfo.setTaskId(taskid);
        pokerActivateInfo.setRunStatus(1);
        pokerActivateInfoMapper.updateById(pokerActivateInfo);

    }

    @Override
    public void endActivate(Integer id) {
        PokerActivateInfo activateInfo = this.getById(id);
        LambdaQueryWrapper<PokerUserActivatInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PokerUserActivatInfo::getTaskId,activateInfo.getTaskId()).eq(PokerUserActivatInfo::getActivateId,activateInfo.getId());
        List<PokerUserActivatInfo> userActivatInfoList = userActivatInfoService.list(wrapper);

        LambdaQueryWrapper<PokerActivateAwardInfo> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(PokerActivateAwardInfo::getActivateId,activateInfo.getId());
        List<PokerActivateAwardInfo> activateAwardInfoList = activateAwardInfoService.list(wrapper1);

        ArrayList<PokerAward> insertAwardList = new ArrayList<>();

        for (PokerUserActivatInfo userActivatInfo : userActivatInfoList) {
            for (PokerActivateAwardInfo activateAwardInfo : activateAwardInfoList) {
                if (activateAwardInfo.getRank()!=null){
                    if (userActivatInfo.getRank().equals(activateAwardInfo.getRank())){
                        JSONArray awardList = JSONUtil.parseArray(activateAwardInfo.getAwardContent());
                        for (int i = 0; i < awardList.size(); i++) {
                            JSONObject jsonObject = awardList.getJSONObject(i);
                            PokerAward pokerAward = new PokerAward();
                            pokerAward.setGoodId(jsonObject.getStr("goodId"));
                            pokerAward.setNum(jsonObject.getDouble("num"));
                            pokerAward.setGoodName(jsonObject.getStr("name"));
                            pokerAward.setIsEnd(0);
                            pokerAward.setServerId(activateInfo.getServerId());
                            pokerAward.setUserId(userActivatInfo.getUserId());
                            pokerAward.setTaskId(userActivatInfo.getTaskId());
                            pokerAward.setSteamId(userActivatInfo.getSteamId());
                            pokerAward.setActivateName(activateInfo.getName());
                            insertAwardList.add(pokerAward);
                        }
                    }
                }
            }
        }
        pokerAwardService.saveBatch(insertAwardList);
        activateInfo.setRunStatus(2);
        this.updateById(activateInfo);
    }

    @Override
    public void eKing(Integer activateId, Integer groupId,List<Integer> joinGroupIds) {
        PokerActivateInfo activateInfo = this.getById(activateId);
        ArrayList<PokerAward> insertAwardList = new ArrayList<>();
        //处理排名奖励结算
        LambdaQueryWrapper<KingTeamVote> voteRankWrapper = new LambdaQueryWrapper<>();
        voteRankWrapper.eq(KingTeamVote::getActivateId,activateId).eq(KingTeamVote::getGroupId,groupId);
        List<KingTeamVote> voteRankList = kingTeamVoteService.list(voteRankWrapper);

        LambdaQueryWrapper<PokerActivateAwardInfo> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(PokerActivateAwardInfo::getActivateId,activateInfo.getId());
        List<PokerActivateAwardInfo> activateAwardInfoList = activateAwardInfoService.list(wrapper1);


        for (KingTeamVote kingTeamVote : voteRankList) {
            User user = userService.getById(kingTeamVote.getUserId());
            for (PokerActivateAwardInfo activateAwardInfo : activateAwardInfoList) {
                if (activateAwardInfo.getRank()!=null){
                    if (kingTeamVote.getRank().equals(activateAwardInfo.getRank())){
                        JSONArray awardList = JSONUtil.parseArray(activateAwardInfo.getAwardContent());
                        for (int i = 0; i < awardList.size(); i++) {
                            JSONObject jsonObject = awardList.getJSONObject(i);
                            PokerAward pokerAward = new PokerAward();
                            pokerAward.setGoodId(jsonObject.getStr("goodId"));
                            pokerAward.setNum(jsonObject.getDouble("num"));
                            pokerAward.setGoodName(jsonObject.getStr("name"));
                            pokerAward.setIsEnd(0);
                            pokerAward.setServerId(activateInfo.getServerId());
                            pokerAward.setUserId(kingTeamVote.getUserId());
                            pokerAward.setTaskId(activateInfo.getTaskId());
                            pokerAward.setSteamId(user.getSteamId());
                            pokerAward.setActivateName(activateInfo.getName());
                            insertAwardList.add(pokerAward);
                        }
                    }
                }
            }
        }
        //参与奖结算
        voteRankWrapper.clear();
        voteRankWrapper.eq(KingTeamVote::getActivateId,activateId).in(KingTeamVote::getGroupId,joinGroupIds);
        List<KingTeamVote> joinTeamVoteList = kingTeamVoteService.list(voteRankWrapper);
        LambdaQueryWrapper<PokerGoodInfo> goodWrapper = new LambdaQueryWrapper<>();
        goodWrapper.eq(PokerGoodInfo::getGoodId,activateInfo.getJoinGoodId());
        PokerGoodInfo goodInfo = goodInfoService.getOne(goodWrapper);

        for (KingTeamVote kingTeamVote : joinTeamVoteList) {
            User user = userService.getById(kingTeamVote.getUserId());
            PokerAward pokerAward = new PokerAward();
            pokerAward.setGoodId(activateInfo.getJoinGoodId());
            pokerAward.setNum(Double.parseDouble(String.valueOf(activateInfo.getJoinGoodNum())));
            pokerAward.setGoodName(goodInfo.getGoodName());
            pokerAward.setIsEnd(0);
            pokerAward.setServerId(activateInfo.getServerId());
            pokerAward.setUserId(kingTeamVote.getUserId());
            pokerAward.setTaskId(activateInfo.getTaskId());
            pokerAward.setSteamId(user.getSteamId());
            pokerAward.setActivateName(activateInfo.getName());
            insertAwardList.add(pokerAward);
        }
        pokerAwardService.saveBatch(insertAwardList);
        activateInfo.setRunStatus(2);
        this.updateById(activateInfo);

    }
}